package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

@Slf4j
@Service
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

	@Autowired
	private TrackInfoMapper trackInfoMapper;
	@Autowired
	private AlbumInfoMapper albumInfoMapper;
	@Autowired
	private VodService vodService;
	@Autowired
	private TrackStatMapper trackStatMapper;

	@Override
	public void saveTrackInfo(TrackInfo trackInfo) {
		Long userId = AuthContextHolder.getUserId();
		//根据专辑id查询专辑图片，在没有声音封面时使用
		AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfo.getAlbumId());
		//2.新增声音
		//2.1 设置声音额外基本信息：用户ID，声音排序序号，状态，来源
		trackInfo.setUserId(userId);
		//根据总声音数来设置排序字段
		trackInfo.setOrderNum(albumInfo.getIncludeTrackCount() + 1);
		trackInfo.setSource(SystemConstant.TRACK_SOURCE_USER);
		//设置为未通过，通过校验后才改为通过
		trackInfo.setStatus(SystemConstant.TRACK_STATUS_NO_PASS);
		if (StringUtils.isEmpty(trackInfo.getCoverUrl())){
			trackInfo.setCoverUrl(albumInfo.getCoverUrl());
		}
		//2.2 远程调用腾讯云点播平台获取音频详情信息，根据详细信息里面的参数填充声音信息
		TrackMediaInfoVo mediaInfoVo = vodService.getMediaInfo(trackInfo.getMediaFileId());
		if (mediaInfoVo != null){
			//BigDecimal：高精度浮点数运算
			trackInfo.setMediaDuration(BigDecimal.valueOf(mediaInfoVo.getDuration()));
			trackInfo.setMediaSize(mediaInfoVo.getSize());
			trackInfo.setMediaType(mediaInfoVo.getType());
		}
		//2.3 新增声音
		trackInfoMapper.insert(trackInfo);

		//3.更新专辑信息（包含声音数量）
		albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount()+1);
		//TODO: 如何实现修改
		albumInfoMapper.updateById(albumInfo);

		Long trackId = trackInfo.getId();
		//4.初始化声音统计信息
		this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_PLAY, 0);
		this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_COLLECT, 0);
		this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_PRAISE, 0);
		this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_COMMENT, 0);

	}

	@Override
	public void saveTrackStat(Long trackId, String statType, int statNum) {
		TrackStat trackStat = new TrackStat();
		trackStat.setTrackId(trackId);
		trackStat.setStatType(statType);
		trackStat.setStatNum(statNum);
		trackStatMapper.insert(trackStat);
	}

	/**
	 * 条件分页查询当前用户声音列表（包含声音统计信息）
	 *
	 * @param pageInfo 分页对象
	 * @param trackInfoQuery 查询条件（用户ID，关键字，审核状态）
	 * @return
	 */
	@Override
	public Page<TrackListVo> getUserTrackPage(Page<TrackListVo> pageInfo, TrackInfoQuery trackInfoQuery) {

		return trackInfoMapper.getUserTrackPage(pageInfo, trackInfoQuery);
	}

	@Override
	public void updateTrackInfo(TrackInfo trackInfo) {
		//1.判断音频文件是否变更
		//1.1 根据声音ID查询声音记录得到“旧”的音频文件标识
		TrackInfo oldTrackInfo = trackInfoMapper.selectById(trackInfo.getId());
		//1.2 判断文件是否被更新，根据文件唯一标识来判断
		String mediaFileIdNew = trackInfo.getMediaFileId();
		String mediaFileIdOld = oldTrackInfo.getMediaFileId();
		if (!mediaFileIdNew.equals(mediaFileIdOld)){
			//文件不相同时，文件的详细信息也会不同，需要从新获取来更改
			TrackMediaInfoVo mediaInfo = vodService.getMediaInfo(mediaFileIdNew);
			trackInfo.setMediaSize(mediaInfo.getSize());
			trackInfo.setMediaType(mediaInfo.getType());
			trackInfo.setMediaDuration(BigDecimal.valueOf(mediaInfo.getDuration()));
			//3.TODO 对内容（文本，音频）进行再次审核
			//旧的音频文件要从云平台删除，不然浪费钱
			vodService.deleteMedia(mediaFileIdOld);
		}
		//设置为不通过，等审核后再优化
		trackInfo.setStatus(SystemConstant.TRACK_STATUS_NO_PASS);

		//审核后进行执行
		trackInfoMapper.updateById(trackInfo);

	}
	/*
	*根据id删除声音
	* 操作表格：声音表，声音统计表，专辑表（声音数量）
	 */
	@Override
	public void removeTrackInfo(Long id) {
		//预存要被删除的id得到相关的专辑号与排序号，不然删除后就找不到了
		TrackInfo deleteTrackInfo = trackInfoMapper.selectById(id);
		Long albumId = deleteTrackInfo.getAlbumId();
		Integer orderNum = deleteTrackInfo.getOrderNum();

		//更新排序号
		LambdaUpdateWrapper<TrackInfo> updateWrapper = new LambdaUpdateWrapper<>();
		//设置更新条件
		updateWrapper.eq(TrackInfo::getAlbumId,albumId);
		updateWrapper.gt(TrackInfo::getOrderNum, orderNum);
		//2.2 修改字段值
		updateWrapper.setSql("order_num = order_num - 1");
		trackInfoMapper.update(null, updateWrapper);
		//3.删除声音表记录
		trackInfoMapper.deleteById(id);
		//4.删除声音统计
		LambdaQueryWrapper<TrackStat> trackStatLambdaQueryWrapper = new LambdaQueryWrapper<>();
		trackStatLambdaQueryWrapper.eq(TrackStat::getTrackId, id);
		trackStatMapper.delete(trackStatLambdaQueryWrapper);

		//5.更新专辑包含声音数量
		AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
		albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() - 1);
		albumInfoMapper.updateById(albumInfo);
		//6.删除点播平台音频文件
		vodService.deleteMedia(deleteTrackInfo.getMediaFileId());
	}
}
